package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    JwtProperties jwtProperties;
    private final static String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 微信登录
     *
     * @param dto
     * @return
     */
    @Override
    public UserLoginVO wxlogin(UserLoginDTO dto){
        //调用方法获取openid
        String openid = getByOpenid(dto.getCode());
        //判断openid是否为空
        if (openid == null){
            //空抛登录异常
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //根据openid查询用户信息
        User user = userMapper.getByOpenid(openid);
        //新用户自动完成注册
        if (user == null){
            user = User.builder()
                    .openid(openid)
                    .name(dto.getCode().substring(2,6))
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }
        Long userId = user.getId();
        log.info("用户id:{}",userId);
        //获取用户id,存入jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,userId);
        //生成jwt令牌
        String authentication = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
        //封装UserLoginVO
        UserLoginVO vo = UserLoginVO.builder()
                .id(userId)
                .token(authentication)
                .openid(openid)
                .build();
        return vo;
    }

    /**
     * 微信登陆凭证校验获取openid
     * @param code
     * @return
     */
    private String getByOpenid(String code) {
        //登录凭证校验
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code", code);
        paramMap.put("grant_type","authorization_code");

        String result = HttpClientUtil.doGet(WX_LOGIN, paramMap);

        JSONObject jsonObject = JSON.parseObject(result);
        String openid = (String) jsonObject.get("openid");

        return openid;
    }
}
